home *** CD-ROM | disk | FTP | other *** search
/ The X-Philes (2nd Revision) / The X-Philes Number 1 (1995).iso / xphiles / hp48hor1 / dec2frac.src < prev    next >
Text File  |  1991-05-29  |  1KB  |  33 lines

  1. %%HP:T(3);
  2. @ DEC2FRAC, by Joseph K. Horn
  3. \<< DUP2 @ Must be two arguments.  Exit now if max denominator < 2,
  4.   IF 1 > SWAP FP AND @ or if decimal fraction is an integer.
  5.   THEN \-> f c @ Store decimal fraction, and max denominator.
  6.  
  7.     \<< 0 1 f @ Calculate only denominators.  Do numerator only at end.
  8.       WHILE OVER c < OVER AND @ Do until bigger than max denominator
  9.       REPEAT INV DUP FP 4 ROLLD IP OVER * ROT + ROT @ This is the
  10.       END DROP DUP2 c @ recursion formula continued fraction expansion.
  11.  
  12.       IF DUP2 > @ Is there a possible "missing" fraction?
  13.       THEN - OVER / CEIL * - @ This is the new, fast "jump backwards".
  14.       ELSE 3 DROPN @ (Sometimes there's no need to jump.)
  15.       END DUP2 1 2 @ Take the new denominator & the previous one, and
  16.  
  17.       START DUP f * 0 RND SWAP / f - ABS SWAP @ turn into fractions.
  18.       NEXT @ See which one's closest to the original decimal fraction.
  19.  
  20.       IF > @ Compare the two solutions, and
  21.       THEN SWAP @ pick the better one.
  22.       END DROP DUP f * 0 RND SWAP @ Calculate the numerator.
  23.     \>> @ End of real work; now clean up the output.
  24.  
  25.     IF DUP ABS 1 > @ Is the denominator greater than 1?
  26.     THEN -3 CF # 5603Eh SYSEVAL @ If so, make output into 'A/B' form.
  27.     ELSE DROP @ Otherwise, get rid of extraneous denominator,
  28.     END @ and exit program.
  29.  
  30.   ELSE DROP @ If bad arguments, do nothing to "decimal fraction", but
  31.   END @ get rid of "maximum denominator" and exit program.
  32. \>>
  33.